using System;
using System.Diagnostics.Tracing;

namespace Beeflys
{
    public sealed class DefaultLogger : ILogger
    {
        public LogLevel Levels { get; set; } = LogLevel.INFO | LogLevel.DEBUG | LogLevel.WARN | LogLevel.ERROR;

        [NonEvent]
        public bool IsEnabled(LogLevel level)
        {
            return this.Levels.HasFlag(level);
        }

        [NonEvent]
        public void Info(string text)
        {
            Console.WriteLine($"[info]{text}");
        }

        [NonEvent]
        public void Debug(string text)
        {
            Console.WriteLine($"[debug]{text}\n{GetLoggerStackTrace()}");
        }

        [NonEvent]
        public void Warn(string text)
        {
            Console.WriteLine($"[warn]{text}");
        }

        [NonEvent]
        public void Error(string text)
        {
            Console.WriteLine($"[error]{text}\n{GetLoggerStackTrace()}");
        }

        private static string GetLoggerStackTrace(bool isInfo = false)
        {
            System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(true);
            System.Diagnostics.StackFrame[] sfs = st.GetFrames();
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            int tempIndex = 0;
            foreach (var item in sfs)
            {
                tempIndex++;
                if (item.GetMethod().DeclaringType.FullName == "Sugar.Logger") continue;
                sb.Append("    ");
                sb.Append($"{item.GetMethod().DeclaringType.FullName}:{item.GetMethod().Name}");
                sb.Append("(");
                System.Reflection.ParameterInfo tempParameterInfo;
                System.Reflection.ParameterInfo[] parameters = item.GetMethod().GetParameters();
                for (int i = 0; i < parameters.Length; i++)
                {
                    tempParameterInfo = parameters[i];
                    sb.Append($"{tempParameterInfo.ParameterType} {tempParameterInfo.Name}");
                    if (i < parameters.Length - 1)
                    {
                        sb.Append(',');
                    }
                }

                sb.Append(')');
                sb.Append($" at ({item.GetFileName()}:{item.GetFileLineNumber()})");
                if (tempIndex != sfs.Length) sb.AppendLine();
                //if (isInfo)
                //{
                //    if (tempIndex == 1)
                //    {
                //        break;
                //    }
                //}
            }

            return sb.ToString();
        }
    }
}
